package com.feixc.xsimple.eventx;

import java.util.Map;

/**
 * 事件处理器基类
 * 
 * @author xuzhigang01
 */
public abstract class BaseEventHandler {

	/**
	 * 获取其他事件处理类
	 */
	@SuppressWarnings("unchecked")
	public <T> T getHandler(Class<T> clazz) {
		return (T) EventDispatcher.getHandler(clazz);
	}

	/**
	 * 获取事件参数
	 */
	@SuppressWarnings("unchecked")
	public <T> T getParam(Map<String, Object> eventParams, String key, Class<T> clazz, boolean required) {
		Object value = eventParams.get(key);
		if (value == null) {
			if (required) {
				throw new IllegalArgumentException(String.format("参数%s不能为空", key));
			}
			return null;
		}

		T v = null;
		try {
			if (value instanceof Number) {
				if (clazz == Byte.class) {
					value = ((Number) value).byteValue();
				} else if (clazz == Short.class) {
					value = ((Number) value).shortValue();
				} else if (clazz == Integer.class) {
					value = ((Number) value).intValue();
				} else if (clazz == Long.class) {
					value = ((Number) value).longValue();
				} else if (clazz == Float.class) {
					value = ((Number) value).floatValue();
				} else if (clazz == Double.class) {
					value = ((Number) value).doubleValue();
				}
			}
			v = (T) value;
		} catch (Exception e) {
			throw new IllegalArgumentException(String.format("参数%s类型不正确", key));
		}
		return v;
	}
}
